package com.jfs.qy.utils;


import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description url参数工具
 * @E-mail cwm3412638@163.com
 * @Author cwm
 * @Date 2022/11/5
 */
public class UrlParameterUtils {
    /**
     * 格式化路径参数 可选参数
     *
     * @param uri uri
     * @param map map
     * @return initUriPathParams
     * @throws UnsupportedEncodingException 异常
     */
    public static String initUriPathParams(String uri, Map<String, Object> map) throws UnsupportedEncodingException {
        String key;
        String value;
        StringBuilder builder = new StringBuilder();
        builder.append(uri);
        builder.append("?");
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            key = entry.getKey();
            value = String.valueOf(entry.getValue());
            String tmpKv;
            tmpKv = String.format(Locale.ROOT, "%s=%s&", URLEncoder.encode(key, "UTF-8"),
                    URLEncoder.encode(value, "UTF-8"));
            builder.append(tmpKv);
        }
        return builder.toString();
    }

    /**
     * 截取url中指定参数值
     *
     * @param url
     * @param filed
     * @return
     */
    public static String getParamByUrl(String url, String filed) {
        String result = "";
        Pattern pXM = Pattern.compile(filed + "=([^&]*)");
        Matcher mXM = pXM.matcher(url);
        while (mXM.find()) {
            result += mXM.group(1);
        }
        return result;
    }
}
